// StockDN.ts
export interface StockItem {
  // 基础信息
  code: string // 股票代码（必填）
  fullCode: string // 完整股票代码（必填）
  name?: string // 股票名称（可选）
  // 价格相关
  price?: number // 最新价格（可选）
  preClose?: number // 昨收价（可选）
  change?: number | string // 涨跌幅（可选）
  // 持仓相关
  cost?: number // 成本价（可选）
  holdings?: number // 持仓数量（可选）
  tax?: number // 税费（可选）
  type?: 'stock' | 'fund' | 'convertible' // 类型区分（股票/基金/可转债）
  // 新增计算字段
  profit?: string | number // 总盈亏
  todayProfit?: string | number // 今日盈亏
  investment?: string | number // 投入金额
  holdingValue?: string | number // 持仓金额（持仓数量 × 当前价格）
  // 保留扩展能力
  [key: string]: any // 允许其他属性
}

// 打开数据库并创建存储对象
const openDB = (): Promise<IDBDatabase> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('StockDB', 1)

    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result
      if (!db.objectStoreNames.contains('stocks')) {
        // 创建存储对象，以code作为主键
        db.createObjectStore('stocks', { keyPath: 'code' })
      }
    }

    request.onsuccess = (event) => {
      resolve((event.target as IDBOpenDBRequest).result)
    }

    request.onerror = (event) => {
      console.error('打开数据库失败:', (event.target as IDBOpenDBRequest).error)
      reject((event.target as IDBOpenDBRequest).error)
    }
  })
}

// 获取所有股票数据
export const getAllStocks = async (): Promise<StockItem[]> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readonly')
    const store = transaction.objectStore('stocks')
    const request = store.getAll()

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error('获取股票数据失败:', request.error)
      reject(request.error)
    }
  })
}

// 根据代码获取股票
export const getStockByCode = async (code: string): Promise<StockItem | null> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readonly')
    const store = transaction.objectStore('stocks')
    const request = store.get(code)

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error(`获取股票 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 添加新股票
export const addStock = async (stock: StockItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.add(stock)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`添加股票 ${stock.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 更新股票
export const updateStock = async (stock: StockItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.put(stock)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`更新股票 ${stock.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 批量更新股票
export const batchUpdateStocks = async (stocks: StockItem[]): Promise<void> => {
  if (stocks.length === 0) {
    return Promise.resolve()
  }

  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')

    // 批量添加所有股票更新操作
    stocks.forEach((stock) => {
      store.put(stock)
    })

    // 事务完成时处理
    transaction.oncomplete = () => {
      console.log(`成功批量更新 ${stocks.length} 条股票数据`)
      resolve()
    }

    // 事务出错时处理
    transaction.onerror = () => {
      console.error('批量更新股票失败:', transaction.error)
      reject(transaction.error)
    }
  })
}

// 删除股票
export const deleteStock = async (code: string): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.delete(code)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`删除股票 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 初始化数据库（如果为空则导入初始数据）
export const initDB = async (initialData: StockItem[]): Promise<void> => {
  const stocks = await getAllStocks()
  if (stocks.length === 0) {
    const db = await openDB()
    return new Promise((resolve, reject) => {
      const transaction = db.transaction('stocks', 'readwrite')
      const store = transaction.objectStore('stocks')

      initialData.forEach((stock) => {
        store.add(stock)
      })

      transaction.oncomplete = () => {
        resolve()
      }

      transaction.onerror = () => {
        console.error('初始化数据库失败:', transaction.error)
        reject(transaction.error)
      }
    })
  }
}
